﻿using System;
using WebFormsMvp.Contrib.Data.Services;
using WebFormsMvp.Contrib.Models;

namespace WebFormsMvp.Contrib.Presenters
{
    /// <summary>
    /// Presenter which provides a <see cref="WebFormsMvp.Contrib.Data.Models.INewsArticle"/> via the <see cref="WebFormsMvp.Contrib.Data.Services.INewsService"/>.
    /// Loaded via QueryString parameter 'id'
    /// </summary>
    /// <remarks>
    /// <para>
    ///     This presenter would need to be inherited from unless the instance of <see cref="WebFormsMvp.Binder.IPresenterFactory"/> 
    ///     used injects the <see cref="WebFormsMvp.Contrib.Data.Services.INewsService"/>.
    /// </para>
    /// <seealso cref="WebFormsMvp.Presenter{TView}"/>
    /// </remarks>
    public class NewsArticlePresenter : Presenter<IView<NewsArticleModel>>
    {
        /// <summary>
        /// The <see cref="WebFormsMvp.Contrib.Data.Services.INewsService"/> for the presenter
        /// </summary>
        protected INewsService dataService;

        /// <summary>
        /// Initializes a new instance of the <see cref="NewsArticlePresenter"/> class.
        /// </summary>
        /// <param name="view">The view.</param>
        /// <param name="dataService">The data service.</param>
        public NewsArticlePresenter(IView<NewsArticleModel> view, INewsService dataService)
            : base(view)
        {
            view.Load += new EventHandler(View_Load);
            this.dataService = dataService;
        }

        /// <summary>
        /// Handles the Load event of the View control, loading the news article from the data service, via the HttpRequest.QueryString["id"]
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected virtual void View_Load(object sender, EventArgs e)
        {
            this.View.Model.NewsArticle = this.dataService.GetNewsArticle(int.Parse(this.Request.QueryString["id"]));
        }

        /// <summary>
        /// Releases the view.
        /// </summary>
        public override void ReleaseView()
        {
            this.View.Load -= new EventHandler(this.View_Load);
        }
    }
}
